from sqlobject import *
from sqlobject.sqlbuilder import *

class Show(SQLObject):
	name = UnicodeCol(notNone = True, unique = True, alternateID = True)
	country = UnicodeCol(default = None)
	status = UnicodeCol(default = None)
	classification = UnicodeCol(default = None)
	genres = UnicodeCol(default = None)
	network = UnicodeCol(default = None)
	airtime = UnicodeCol(default = None)
	runtime = IntCol(default = None)
	skipUpdate = BoolCol(default = False)

	seasons = SQLMultipleJoin("Season", joinColumn="show")
	mgenres = SQLRelatedJoin("Genre")

class Genre(SQLObject):
	name = UnicodeCol(notNone = True, unique = True, alternateID = True)

	shows = SQLRelatedJoin("Show")

class Season(SQLObject):
	show = ForeignKey("Show", cascade = True)
	number = IntCol(default = None)

	episodes = SQLMultipleJoin("Episode", joinColumn="season")

class Episode(SQLObject):
	season = ForeignKey("Season", cascade = True)
	number = IntCol(default = None)
	title = UnicodeCol(notNone = True)
	date = DateCol(default = None)

class ShowAlternateNames(SQLObject):
	name = UnicodeCol(notNone = True, unique = True, alternateID = True)
	show = ForeignKey("Show", cascade = True)

class UnknownShows(SQLObject):
	name = UnicodeCol(notNone = True, unique = True, alternateID = True)
	checked = BoolCol(default = False)

class Feed(SQLObject):
	url = UnicodeCol(notNone = True, unique = True, alternateID = True)
	name = UnicodeCol(notNone = True)
	eTag = UnicodeCol(default = None)
	lastModified = DateTimeCol(default = None)
	redownload = BoolCol(default = False)

class RegExp(SQLObject):
	pattern = UnicodeCol(notNone = True)
	show = ForeignKey("Show", cascade = True, default = None)

class BlacklistRegExp(SQLObject):
	pattern = UnicodeCol(notNone = True)

class Match(SQLObject):
	value = UnicodeCol(notNone = True)
	show = ForeignKey("Show", cascade = True)
	season_number = IntCol(default = None)
	episode_number = IntCol(default = None)

class Download(SQLObject):
	name = UnicodeCol(notNone = True, unique = True, alternateID = True)

def init(uri = None):
	if not uri:
		try:
			from ConfigParser import SafeConfigParser as ConfigParser
		except ImportError:
			from ConfigParser import ConfigParser
		config = ConfigParser()
		import os
		config.read(os.path.join(os.environ['HOME'], '.wjs.ini'))
		uri = config.get("dsn", "shows")
	connection = connectionForURI(uri)
	sqlhub.processConnection = connection
	Show.createTable(ifNotExists = True)
	Season.createTable(ifNotExists = True)
	Episode.createTable(ifNotExists = True)
	Genre.createTable(ifNotExists = True)
	ShowAlternateNames.createTable(ifNotExists = True)
	UnknownShows.createTable(ifNotExists = True)
	Feed.createTable(ifNotExists = True)
	RegExp.createTable(ifNotExists = True)
	BlacklistRegExp.createTable(ifNotExists = True)
	Match.createTable(ifNotExists = True)
	Download.createTable(ifNotExists = True)

def _buildGenreList():
	Genre.dropTable(ifExists = True)
	Genre.createTable(ifNotExists = True)
	for show in Show.select():
		if show.genres:
			for genre_name in show.genres.split(' | '):
				try:
					genre = Genre.byName(genre_name)
				except SQLObjectNotFound:
					genre = Genre(name = genre_name)
				genre.addShow(show)

def GetShow(name):
	try:
		return Show.byName(name)
	except SQLObjectNotFound:
		pass
	try:
		return ShowAlternateNames.byName(name).show
	except SQLObjectNotFound:
		pass
	try:
		UnknownShows(name = name)
	except dberrors.DuplicateEntryError:
		pass
	return None

def add_feed(url, redownload = True):
	import feedparser
	d = feedparser.parse(url)
	return Feed(url = url, name = d.feed.title, redownload = redownload)

def add_pattern(show_name, pattern):
	return RegExp(pattern = pattern, show = GetShow(show_name))

def add_shows_pattern():
	for show in Show.select(Show.q.skipUpdate == False):
		name = show.name.encode('UTF-8')
		pname = name.lower().translate(None, ':?!&')
		pos = pname.find('(')
		if pos >= 0:
			pname = pname[:pos]
		pattern = '^' + pname.strip().replace(' ', r'\.') + '.*$'
		if RegExp.select(RegExp.q.pattern == pattern).count() == 0:
			RegExp(pattern = pattern, show = show)



if __name__ == '__main__':
	init()
	import sys
	if len(sys.argv) > 1:
		cmd = sys.argv[1]
		if cmd == 'feed':
			add_feed(sys.argv[2])
		elif cmd == 'pattern':
			add_pattern(sys.argv[2], sys.argv[3])
		elif cmd == 'shows':
			add_shows_pattern()
